package com.bwhx.eruler.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.bwhx.eruler.bean.Page;
import com.bwhx.eruler.bean.Ruler;
import com.bwhx.eruler.bean.Department;
import com.bwhx.eruler.service.DepartmentService;
/**
 * 部门管理
 * @author Cuilitang
 *
 */

@Controller
public class DepartmentController extends BaseController {
	
	@Autowired
	DepartmentService deptService;
	
	@ResponseBody
	@RequestMapping(value = "/page.deptList.ashx")
	 public Map deptList(Integer page,Integer rows,Department d) {
		//每页的开始记录
        int start = (page-1)*rows;
        Page p = new Page(start,rows,d);
		Map map = new HashMap();
		try{
			List<Department> list = deptService.list(p);
			Integer count = deptService.count(d);
			log.info(list);
			log.info(count);
			
			map.put("total",count );//total键 存放总记录数，必须的  
			map.put("rows",list);//rows键 存放每页记录 list 
			for (Department dept : list) {
				log.info(dept);
			}
			
		}catch(Exception e){
			log.error(getTrace(e));
			map.put("meg", "失败！");
			map.put("status", "0");
		}
		
	    return map;  
	  }
	
	@ResponseBody
	@RequestMapping(value = "/page.saveOrUpdateDepartment.ashx")
	public String saveOrUpdateDepartment(Department dept) {
		try{
			if(dept.getdId()==-1){
				List<Department> list = deptService.findByName(dept.getdName());
				if(list.size()!=0){return "conflict";}
				deptService.insert(dept);
			}else{
				log.info("修改dept成功");
				deptService.update(dept);
			}
			
		}catch(Exception e){
			log.error(getTrace(e));
			return "fail";
		}
		
		
	    return "success";  
	  }
	
	
	@ResponseBody
	@RequestMapping(value = "/page.get.ashx")
	 public Department get(Integer dId) {
		
		Department d = deptService.get(dId);
	    return d;  
	 }
	
	
	@ResponseBody
 	@RequestMapping(value = "/page.everyone.getDeptById.ashx")
	 public List<Department> getDeptById(Integer dId) {
		
 		List<Department> arrayList = new ArrayList<Department>();
 		Department d = deptService.get(dId);
		arrayList.add(d);
	    return arrayList;  
	 }
	
	
	
	@ResponseBody
	@RequestMapping(value = "/page.deptListAll.ashx")
	 public List<Department>  deptListAll() {
		
		List<Department> ld = deptService.deptListAll();
	    return ld;  
	 }
	
	@ResponseBody
@RequestMapping(value = "/page.deptdel.ashx")
 public Map<String,String> OfflineOrderDel(@RequestParam String dId){
	Map<String,String> resultMap = new HashMap<String, String>();
	resultMap.put("status", "1");
	deptService.del(dId);

    return resultMap;  
  }

	

}
